//
//  FacebookSignInHelper.m
//  Cycling
//
//  Created by CSS on 6/5/23.
//

#import "FacebookSignInHelper.h"

#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKCoreKit/FBSDKCoreKit+Internal.h>

#import "UserRequest.h"
#import "PerfectMessageViewController.h"

#import "Cycling-Swift.h"
#import "BaseViewController.h"
#import "MineRootViewController.h"
#import "BaseNavigationController.h"

@implementation BaseViewController (SupportFacebookSign)

- (void)openFacebookForLogin
{
    FBSDKLoginManagerLoginResultBlock loginResultBlock = ^(FBSDKLoginManagerLoginResult *result, NSError *error) {
        if(error || result.isCancelled) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self removeLoadingView];
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showLoadingViewWithText:@""];
            });
            NSString *facebookId =  result.token.tokenString;
            //用户的facebookId 传给后台 判断该用户是否绑定手机号，如果绑定了直接登录，如果没绑定跳绑定手机号页面
            [UserRequest thirdLoginWithPlatform:@"facebook" code:facebookId result:^(UserModel *user) {
                if (user) {
                    [[NSUserDefaults standardUserDefaults] setValue:user.token forKey:@"Token"];
                    [user updateUserInfo];
                    [UserModel setLoginSatus:YES];
                    if(user.isNewUser) {
                        PerfectMessageViewController *vc = [[PerfectMessageViewController alloc] init];
                        [self.navigationController pushViewController:vc animated:YES];
                    } else {
                        appDelegate.window.rootViewController = [[BaseNavigationController alloc] initWithRootViewController:[[BaseTabBarController alloc] init]];
                        [appDelegate.window makeKeyAndVisible];
                        [MineRootViewController postShowOpenHealthPermissionAlertNotification];
                    }
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self removeLoadingView];
                });
            }];
        }
    };
    
    FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
    if([FBSDKAccessToken currentAccessToken] != nil) {
        [loginManager reauthorizeDataAccess:self handler:loginResultBlock];
        return;
    }
    [loginManager logInWithPermissions:@[@"public_profile"] fromViewController:self handler:loginResultBlock];
}

@end
